package com.tid.hbasees.utils;

import com.google.common.base.Optional;
import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;

@Component
public class JsonHelper {
    private static final Logger LOG = Logger.getLogger(JsonHelper.class);

    private ObjectMapper mapper;

    @PostConstruct
    public void init() {
        this.mapper = new ObjectMapper();
    }

    public ObjectMapper getMapper() {
        return this.mapper;
    }

    public <T> Optional<T> readValue(String json, Class<T> clazz) {
        try {
            return Optional.of(this.mapper.readValue(json, clazz));
        } catch (IOException e) {
            e.printStackTrace();
            LOG.error("failed to convert json[" + json + "] due to " + e.getMessage());
            return Optional.absent();
        }
    }

    public <T> String writeValue(T instance) {
        try {
            return mapper.writeValueAsString(instance);
        } catch (IOException e) {
            e.printStackTrace();
            LOG.error("failed to convert object to json due to " + e.getMessage());
            return "";
        }
    }
}
